package com.weijian.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.weijian.dal.dataobject.Article;
import com.weijian.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 同步数据库数据到向量数据库
 */
@Slf4j
public class SyncVectorUtil {

    // 记录上次同步的时间
    private static LocalDateTime lastSyncTime = LocalDateTime.of(1970, 1, 1, 0, 0, 0);

    public static void syncIfUpdated(ArticleService ArticleService, VectorStore vectorStore) {
        // 1. 检查数据库是否有更新
        List<Article> updatedRecords = ArticleService.listUpdatedSince(lastSyncTime);
        log.info(String.valueOf(lastSyncTime));
        if (CollectionUtils.isEmpty(updatedRecords)) {
            log.info("数据库没有更新，跳过同步");
            return;
        }
        List<String> idList = updatedRecords.stream()
                .filter(record -> Boolean.TRUE.equals(record.getDeleted()))
                .map(record -> String.valueOf(record.getId()))
                .toList();
        if (CollectionUtil.isNotEmpty(idList)) {
            vectorStore.delete(idList);
        }
        List<Article> updateList = updatedRecords.stream()
                .filter(record -> Boolean.FALSE.equals(record.getDeleted()))
                .toList();
        if (CollectionUtil.isNotEmpty(updateList)) {
            extracted(updateList, vectorStore);
        }
        lastSyncTime = LocalDateTime.now();
    }

    public static void syncInit(ArticleService ArticleService, VectorStore vectorStore) {
        // 1. 检查数据库是否有数据
        List<Article> ArticleList = ArticleService.list();
        if (CollectionUtils.isEmpty(ArticleList)) {
            log.info("数据库没有数据，跳过同步");
            return;
        }
//        extracted(ArticleList, vectorStore);
        lastSyncTime = LocalDateTime.now();
    }

    /*private static void extracted(List<Article> articleList, VectorStore vectorStore) {
        int total = articleList.size();
        TokenTextSplitter tokenTextSplitter = new TokenTextSplitter(3000, 300, 5, 5000, true);
        HashMap<String, Object> map = new HashMap<>();
        log.info("数据库开始同步es, 总条数： {}", total);
        articleList.stream()
                .map(article -> {
                    map.put("id", article.getId());
                    map.put("title", article.getTitle());
                    return new Document(String.valueOf(article.getId()), article.getContent(), map);
                }).forEach(document -> {
                    List<Document> documents = tokenTextSplitter.split(document);
                    vectorStore.add(documents);
                });
        log.info("数据库结束同步es, 总条数： {}", total);
    }*/

    /**
     * 不对文本做切分
     */
    private static void extracted(List<Article> articleList, VectorStore vectorStore) {
        int total = articleList.size();
        HashMap<String, Object> map = new HashMap<>();
        log.info("数据库开始同步es, 总条数： {}", total);
        articleList.stream()
                .map(article -> {
                    map.put("id", article.getId());
                    map.put("title", article.getTitle());
                    return new Document(String.valueOf(article.getId()), article.getContent(), map);
                }).forEach(document -> {
                    vectorStore.add(List.of(document));
                });
        log.info("数据库结束同步es, 总条数： {}", total);
    }

}
